import { Component, OnInit, ViewChild } from '@angular/core';
import { ApiService } from '../../../core/api.service';
import { DomSanitizer } from '@angular/platform-browser';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ReuseTabService } from '@delon/abc';
import { ActivatedRoute, Params } from '@angular/router';
import { TableRowMergeComponent } from '../../../core/tableRowMerge.component';
import { MaintenanceComponent } from '../../../layout/components/maintenance.component';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-yearworkexam',
    templateUrl: './yearworkexam.component.html',
    styleUrls: ['./yearworkexam.component.less']
})
export class YearworkexamComponent implements OnInit {
    @ViewChild('mtecom', { static: true }) mtecom: MaintenanceComponent;
    allChecked = false;
    indeterminate = false;
    displayData = [];
    data: any = [];
    yearpageValue = '50';
    yearselectedValue = '50';
    step1: any = true;
    rowTotalTable1 = 0;
    pageIndexTable1 = 1;
    rowpageTable1 = 1;
    pageTotal1 = '';

    displayData2 = [];
    data2: any = [];
    listpageValue = '50';
    listselectedValue = '50';
    step2: any = false;
    rowTotalTable2 = 0;
    pageIndexTable2 = 1;
    rowpageTable2 = 1;
    pageTotal2 = '';

    selectedValue3 = '';
    selectedValue4 = '';
    selectedData: any;
    workData: any;
    getyearlist: any;
    devinfolist: any;
    showstep3 = 'none';

    tempEquipmentIds: any = [];
    tempEquipmentGroup: any = [];
    allgongshi: any = 0;
    allshebei: any = 0;
    tempstepyear = '';
    tempsteporgid = '';
    newdest = '';
    yearworkremarks = '';
    equipmentSaveIndex = 0;
    viewEquipment: any = {};
    workdateMonth: any = [];
    workdateMonthBackup: any = [];
    linetype = '';
    paramStatus = '';
    tabsetIndex = 0;
    tabsTypevcCj = '';
    placeValue = '0';

    addYearVisible = false;
    operateYearVisible = false;
    operateyearData = { 'type': '', 'title': '', 'data': [] };
    statusYearVisible = false;
    statusYearNid = '';
    addWorkVisible = false;
    addWorkButton = false;
    placeId = '';
    vcStatus = '';

    workareaid: any = '';
    chejianIndex = '';
    datachejian: any = [];
    datachejian2: any = [];
    datachejian3: any = [];
    cjstep1 = false;
    cjstep2 = false;
    cjstep3 = false;
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };

    constructor(
        private apiService: ApiService,
        private tabmercom: TableRowMergeComponent,
        private reuseTabService: ReuseTabService,
        private message: NzMessageService,
        private activatedRoute: ActivatedRoute,
        private http: _HttpClient,
        private sanitizer: DomSanitizer
    ) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) => {
            this.paramStatus = params.status;
            switch (this.paramStatus) {
                case 'gcs':
                    this.reuseTabService.title = '段年度计划';
                    break;
                case 'jskz':
                    this.reuseTabService.title = '技术科长审核';
                    break;
                case 'dz':
                    this.reuseTabService.title = '段长审核';
                    break;
                case 'qzbh':
                    this.reuseTabService.title = '年表计划驳回';
                    break;
            }
            this.reload();
        });
    }
    reload() {
        this.readyload(this.rowpageTable1, this.yearpageValue);
    }
    tabsetChange(e) {
        this.tabsetIndex = e;
        switch (this.tabsetIndex) {
            case 0:// 段
                switch (this.paramStatus) {
                    case 'jskz':
                        this.tabsTypevcCj = '3';
                        break;
                    default:
                        this.tabsTypevcCj = '2';
                        break;
                }
                break;
            case 1:// 车间
                this.tabsTypevcCj = '1';
                break;
            case 2:// 工区
                this.tabsTypevcCj = '0';
                break;
        }
        this.backstep();
    }
    _onReuseInit() {
        this.backstep();
    }
    // // 加一行
    // addequipment() {
    //     this.devinfolist.push({ 'ALLDEV': '', 'VC_MONTH$DAYS': '', 'N_WORK$CNT': '0', 'VC_WORK$DAY$DESC': this.newdest, 'N_TOTAL$WORK': '0', 'vcDevGroup': '', 'VC_STATION': this.selectedValue3, 'VC_STATIONNAME': '', 'VC_WORKLEVEL': this.selectedValue4, 'VC_WORKLEVELNAME': '' });
    // }
    // // 删一行
    // delequipment(i) {
    //     this.devinfolist.splice(i, 1);
    //     // 计算设备总数&合计工时
    //     this.allEquipmentCount();
    // }
    // 工区第一页
    chejianData1() {
        this.datachejian = [];

        this.apiService.getAllChejian('0').subscribe((res: any) => {
            this.datachejian = res;
            this.cjstep1 = true;
            this.cjstep2 = false;
            this.cjstep3 = false;
            this.showstep3 = 'none';
        });
    }
    // 工区第二页
    chejianData2(index) {
        this.chejianIndex = index;
        this.datachejian2 = [];

        this.yarnexamData(1, this.yearpageValue, this.paramStatus, this.tabsTypevcCj, this.datachejian[index].opValue).subscribe((res: any) => {
            if (res.type === 'success') {
                this.datachejian2 = res.data.pageList;
                if (this.datachejian2.length) {
                    this.pageTotal1 = res.data.pageCount;
                    this.rowTotalTable1 = res.data.pageCount;
                    this.datachejian2 = this.checkDisabled(this.datachejian2, this.tabsTypevcCj);
                }
                this.cjstep1 = false;
                this.cjstep2 = true;
                this.cjstep3 = false;
                this.showstep3 = 'none';
            }
        });
    }
    // 工区第三页
    chejianData3(page, N_YEAR, orgid, row, filter, linetype, N_ID) {
        this.statusYearNid = N_ID;
        this.linetype = linetype;
        this.rowpageTable2 = page;
        this.pageIndexTable2 = page;
        this.tempstepyear = N_YEAR;
        this.tempsteporgid = orgid;
        this.datachejian3 = [];

        this.yarnexamApprove(page, N_YEAR, orgid, row, filter, linetype, this.paramStatus).subscribe((res: any) => {
            if (res.type === 'success') {
                this.datachejian3 = res.data.pageList;
                if (this.datachejian3.length) {
                    this.pageTotal2 = res.data.pageCount;
                    this.rowTotalTable2 = res.data.pageCount;
                    for (const item of this.datachejian3) {
                        // 处理换行
                        item.REDEVS = item.DEVS ? this.sanitizer.bypassSecurityTrustHtml(item.DEVS) : ' ';
                        item.REVC_NOTE = item.VC_NOTE && item.VC_NOTE !== 'null' ? this.sanitizer.bypassSecurityTrustHtml(item.VC_NOTE.replace(/\[br\]/g, '<br>').replace(/\[nbsp\]/g, ' ')) : ' ';
                        item.disabled = true;
                    }
                    // 表格合并
                    this.tabmercom.mergeRowSet('VC_CLASS,VC_ITEM$NAME,VC_RECYCLE$DESC,VC_UNIT,DEVSUMS,REVC_NOTE', this.datachejian3, (tableData) => {
                        this.datachejian3 = tableData;
                    });
                }
                this.cjstep1 = false;
                this.cjstep2 = false;
                this.cjstep3 = true;
                this.showstep3 = 'none';
            }
        });
    }
    // 第四页详情数据
    chejianData4(index, itemid, nid, type) {
        this.mtecom.getData(this.datachejian3, index, itemid, nid, type, (yearlist, devlist) => {
            this.getyearlist = yearlist;
            this.devinfolist = devlist;
        }, this.tempsteporgid);
        this.cjstep1 = false;
        this.cjstep2 = false;
        this.cjstep3 = false;
        this.showstep3 = 'block';
    }
    publicData(page, rows) {
        this.data = [];

        this.apiService.workshopExamine(page, rows, this.tabsTypevcCj).subscribe((res: any) => {
            if (res.type === 'success') {
                this.data = res.data.pageList;
                if (this.data.length) {
                    this.pageTotal1 = res.data.pageCount;
                    this.rowTotalTable1 = res.data.pageCount;
                    this.data = this.checkDisabled(this.data, this.tabsTypevcCj);
                }
                this.step1 = true;
                this.step2 = false;
                this.showstep3 = 'none';
            }
        });
    }
    publicData2(page, rows) {
        this.data = [];
        this.yarnexamData(page, rows, this.paramStatus, this.tabsTypevcCj, '').subscribe((res: any) => {
            if (res.type === 'success') {
                this.data = res.data.pageList;
                if (this.data.length) {
                    this.pageTotal1 = res.data.pageCount;
                    this.rowTotalTable1 = res.data.pageCount;
                    this.data = this.checkDisabled(this.data, this.tabsTypevcCj);
                }
                this.step1 = true;
                this.step2 = false;
                this.showstep3 = 'none';
            }
        });
    }
    checkDisabled(data, type) {
        for (const item of data) {
            switch (type) {
                case '3':
                    switch (item.VC_STATUS) {
                        case '1':
                        case '5':
                            item.disabled = false;
                            break;
                        default:
                            item.disabled = true;
                            break;
                    }
                    break;
                case '2':
                    switch (this.paramStatus) {
                        case 'dz':
                            switch (item.VC_STATUS) {
                                case '2':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                        case 'qzbh':
                            switch (item.VC_STATUS) {
                                case '4':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                        case 'gcs':
                            switch (item.VC_STATUS) {
                                case '0':
                                case '3':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                    }
                    break;
                case '1':
                    switch (this.paramStatus) {
                        case 'dz':
                            switch (item.VC_STATUS) {
                                case '4':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                        case 'qzbh':
                            switch (item.VC_STATUS) {
                                case '7':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                        case 'jskz':
                            switch (item.VC_STATUS) {
                                case '2':
                                case '8':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                        case 'gcs':
                            switch (item.VC_STATUS) {
                                case '1':
                                case '5':
                                    item.disabled = false;
                                    break;
                                default:
                                    item.disabled = true;
                                    break;
                            }
                            break;
                    }
                    break;
                case '0':
                    item.disabled = false;
                    break;

                default:
                    item.disabled = false;
                    break;
            }
        }
        return data;
    }
    formatData(data) {
        if (!data) {
            data = '';
        }
        return data;
    }
    deleteItem(id) {
        if (!id) {
            return;
        }
        const param = { nnDID: id };
        this.apiService.yearlyDataDelete(param).subscribe(res => {
            if (res.type === 'success') {
                this.message.success('删除成功');
                this.mainBackPage();
            } else {
                this.message.success('删除失败');
            }
        });
    }
    // 第一页列表数据
    readyload(page, rows) {
        switch (this.paramStatus) {
            case 'gcs':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.tabsTypevcCj = '2';
                        this.publicData(page, rows);
                        break;
                    case 1:// 车间
                        this.tabsTypevcCj = '1';
                        this.publicData(page, rows);
                        break;
                    case 2:// 工区
                        this.tabsTypevcCj = '0';
                        this.chejianData1();
                        break;
                }
                break;
            case 'jskz':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.tabsTypevcCj = '3';
                        this.publicData(page, rows);
                        break;
                    case 1:// 车间
                        this.tabsTypevcCj = '1';
                        this.publicData2(page, rows);
                        break;
                    case 2:// 工区
                        this.tabsTypevcCj = '0';
                        this.chejianData1();
                        break;
                }
                break;
            case 'dz':
            case 'qzbh':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.tabsTypevcCj = '2';
                        this.publicData2(page, rows);
                        break;
                    case 1:// 车间
                        this.tabsTypevcCj = '1';
                        this.publicData2(page, rows);
                        break;
                    case 2:// 工区
                        this.tabsTypevcCj = '0';
                        this.chejianData1();
                        break;
                }
                break;
        }
        this.pageIndexTable1 = page;
    }
    // 第二页列表数据
    startstep(page, N_YEAR, orgid, row, filter, linetype, N_ID, VC_STATUS) {
        this.vcStatus = VC_STATUS;
        switch (this.paramStatus) {
            case 'gcs':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.startstepSecond1(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        // 控制显示新增作业按钮
                        if (this.vcStatus === '0' || this.vcStatus === '3') {
                            this.addWorkButton = true;
                        }
                        break;
                    case 1:// 车间
                        this.startstepSecond1(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        // 控制显示新增作业按钮
                        if (this.vcStatus === '1') {
                            this.addWorkButton = true;
                        }
                        break;
                    case 2:// 工区
                        this.chejianData2(this.chejianIndex);
                        break;
                }
                break;
            case 'jskz':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.startstepSecond1(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        // 控制显示新增作业按钮
                        if (this.vcStatus === '1' || this.vcStatus === '5') {
                            this.addWorkButton = true;
                        }
                        break;
                    case 1:// 车间
                        this.startstepSecond2(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        break;
                    case 2:// 工区
                        this.chejianData2(this.chejianIndex);
                        break;
                }
                break;
            case 'dz':
            case 'qzbh':
                switch (this.tabsetIndex) {
                    case 0:// 段
                        this.startstepSecond2(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        break;
                    case 1:// 车间
                        this.startstepSecond2(page, N_YEAR, orgid, row, filter, linetype, N_ID);
                        break;
                    case 2:// 工区
                        this.chejianData2(this.chejianIndex);
                        break;
                }
                break;
        }
    }
    startstepSecond1(page, N_YEAR, orgid, row, filter, linetype, N_ID) {
        this.statusYearNid = N_ID;
        this.linetype = linetype;
        this.rowpageTable2 = page;
        this.pageIndexTable2 = page;
        this.tempstepyear = N_YEAR;
        this.tempsteporgid = orgid;
        this.data2 = [];

        this.apiService.workshopApprove(page, N_YEAR, orgid, row, filter, linetype, this.tabsTypevcCj).subscribe((res: any) => {
            if (res.type === 'success') {
                this.data2 = res.data.pageList;
                this.startstepResult(res);
            }
        });
    }
    startstepSecond2(page, N_YEAR, orgid, row, filter, linetype, N_ID) {
        this.statusYearNid = N_ID;
        this.linetype = linetype;
        this.rowpageTable2 = page;
        this.pageIndexTable2 = page;
        this.tempstepyear = N_YEAR;
        this.tempsteporgid = orgid;
        this.data2 = [];

        this.yarnexamApprove(page, N_YEAR, orgid, row, filter, linetype, this.paramStatus).subscribe((res: any) => {
            if (res.type === 'success') {
                this.data2 = res.data.pageList;
                this.startstepResult(res);
            }
        });
    }
    startstepResult(res) {
        if (this.data2.length) {
            this.pageTotal2 = res.data.pageCount;
            this.rowTotalTable2 = res.data.pageCount;
            for (const item of this.data2) {
                // 处理换行
                item.REDEVS = item.DEVS ? this.sanitizer.bypassSecurityTrustHtml(item.DEVS) : ' ';
                item.REVC_NOTE = item.VC_NOTE && item.VC_NOTE !== 'null' ? this.sanitizer.bypassSecurityTrustHtml(item.VC_NOTE.replace(/\[br\]/g, '<br>').replace(/\[nbsp\]/g, ' ')) : ' ';
            }
            // 表格合并
            this.tabmercom.mergeRowSet('VC_CLASS,VC_ITEM$NAME,VC_RECYCLE$DESC,VC_UNIT,DEVSUMS,REVC_NOTE', this.data2, (tableData) => {
                this.data2 = tableData;
            });
        }
        this.step1 = false;
        this.step2 = true;
        this.showstep3 = 'none';
    }
    // 筛选数据
    yearFilterData(data) {
        let url = '';
        data.yearstatus ? url += '&yearstatus=' + data.yearstatus : url += '';
        data.protype ? url += '&protype=' + data.protype : url += '';
        data.level ? url += '&level=' + data.level : url += '';
        this.startstep(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, url, this.linetype, this.statusYearNid, this.vcStatus);
    }
    // 返回第一页
    backstep() {
        // 切换内部tabs重置所有step
        this.step1 = false;
        this.step2 = false;
        this.showstep3 = 'none';
        this.rowpageTable2 = 1;
        this.pageIndexTable2 = 1;
        this.cjstep1 = false;
        this.cjstep2 = false;
        this.cjstep3 = false;
        this.showstep3 = 'none';
        this.addWorkButton = false;

        switch (this.tabsTypevcCj) {
            case '3':// 参数是jskz段年表值就为3
            case '2':
            case '1':
                this.reload();
                break;
            case '0':
                this.chejianData1();
                break;
        }
    }
    // 返回第二页
    backstep2() {
        // 工区刷新第三页，其他刷新第二页
        if (this.tabsetIndex === 2) {
            this.chejianData3(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid);
        } else {
            this.startstep(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid, this.vcStatus);
        }
    }
    cjbackstep(type) {
        switch (type) {
            case '4':
                this.chejianData3(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid);
                break;
            case '3':
                this.chejianData2(this.chejianIndex);
                break;
            case '2':
                this.chejianData1();
                break;
        }
    }
    mainBackPage() {
        switch (this.tabsTypevcCj) {
            case '3':// 参数是jskz段年表值就为3
            case '2':// 段
            case '1':// 车间
                this.startstep(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid, this.vcStatus);
                break;
            case '0':// 工区则是返回第三页 
                this.cjbackstep('4');
                break;
        }
    }
    // 分页数量-第一页
    yearselectedChange() {
        this.yearpageValue = this.yearselectedValue;
        this.reload();
    }
    // 分页数量-第二页
    listselectedChange() {
        this.listpageValue = this.listselectedValue;
        this.startstep(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid, this.vcStatus);
    }
    // 第三页详情数据
    maintain(index, itemid, nid, type) {
        this.mtecom.getData(this.data2, index, itemid, nid, type, (yearlist, devlist) => {
            this.getyearlist = yearlist;
            this.devinfolist = devlist;
        }, this.tempsteporgid);
        this.step1 = false;
        this.step2 = false;
        this.showstep3 = 'block';
    }
    // 计算设备总数&合计工时
    allEquipmentCount() {
        let allcnt = 0;
        let alltot = 0;
        for (const item of this.devinfolist) {
            allcnt = allcnt + Number(item.N_TOTAL$WORK);
            alltot = alltot + Number(item.N_WORK$CNT);
        }
        this.allgongshi = allcnt;
        this.allshebei = alltot;
    }
    // 年表段审批-审批数据
    yarnexamApprove(page, year, orgid, rows, filter, linetype, type) {
        const url = environment.apiBase + '/csmis/ymyear/ymtyearwork/getsegyearworkplan.jwt?page=' + page + '&rows=' + rows + '&yearnum=' + year + '&orgid=' + orgid + '&linetype=' + linetype + '&type=' + type + filter;
        return this.http.get(url);
    }
    // 年表段审批-列表数据
    yarnexamData(page, rows, type, vcCj, orgid) {
        const url = environment.apiBase + '/csmis/ymyear/ymtyearwork/getsegyearmwork.jwt?orgid=' + orgid + '&vcCj=' + vcCj + '&type=' + type + '&page=' + page + '&rows=' + rows;
        return this.http.get(url);
    }
    // 全选
    checkAll(value: boolean): void {
        this.displayData.forEach(data => {
            if (!data.disabled) {
                data.checked = value;
            }
        });
        this.refreshStatus();
    }
    currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
        this.displayData = $event;
        this.refreshStatus();
    }
    refreshStatus(): void {
        const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked == true);
        const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
    }
    rowChangeTable1(ev) {
        this.rowpageTable1 = ev;
        this.reload();
    }
    currentPageDataChange2($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
        this.displayData2 = $event;
    }
    rowChangeTable2(ev) {
        this.rowpageTable2 = ev;
        this.startstep(this.rowpageTable2, this.tempstepyear, this.tempsteporgid, this.listpageValue, '', this.linetype, this.statusYearNid, this.vcStatus);
    }
    // 显示[新编]弹出层
    yearShowModal() {
        this.addYearVisible = true;
    }
    yearHideModal() {
        this.addYearVisible = false;
    }
    // 显示[提报/删除/批准/驳回]弹出层
    operateShowModal(type, title) {
        this.operateyearData.type = type;
        this.operateyearData.title = title;
        this.operateyearData.data = this.displayData;
        this.operateYearVisible = true;
    }
    operateHideModal() {
        this.operateYearVisible = false;
    }
    // 显示[状态]弹出层
    statusShowModal(nid) {
        this.statusYearNid = nid;
        this.statusYearVisible = true;
    }
    statusHideModal() {
        this.statusYearVisible = false;
    }
    // 显示[作业项目]弹出层
    addWorkShowModal() {
        switch (this.tabsetIndex) {
            case 0:
                this.placeId = '2';
                break;
            case 1:
                this.placeId = '1';
                break;
            case 2:
                this.placeId = '0';
                break;
        }
        this.addWorkVisible = true;
    }
    addWorkHideModal() {
        this.addWorkVisible = false;
    }
}
